import groovy.json.JsonSlurper
import groovy.sql.Sql
import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils;
import wsd.sys.jdbcManager;
import wsd.sys.singlecz.singleczbean
import javax.faces.event.ValueChangeEvent
import org.primefaces.event.SelectEvent
import org.primefaces.event.UnselectEvent
import wsd.appsys.sp.*
import wsd.sys.user.UserBean;
import javax.faces.context.FacesContext;
import org.primefaces.PrimeFaces
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.file.UploadedFile;
import org.primefaces.util.SerializableSupplier;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import java.math.BigDecimal
import java.util.Random;

public execute(o) {
    return new mc(o)
}

class mc {
    def mypara
    def carlist = []
    def lbselectrow
    def dialog
    def dialog1
    def createdate //创建日期
    def zhaochelx //找车类型
    def zhaochegs //找车公司
    def zhaochegys //找车供应商
    def zhaochefzr //找车负责人
    def zhaochesfd //找车始发地
    def zhaochemdd //找车目的地
    def zhaochebz //找车备注
    def zhaochexxdz //找车始发地详细地址
    def zhaochesl //找车数量
    def zhaocheds //找车吨数
    def zckz = true //找车控制
    def bckz = false //保存控制
    def cxzczdr
    def cxzcfzr
    def cxzcksdate
    def cxzxjsdate
    java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd")
    def currentTime = formatter.format(new Date())//当前时间
    public mc(m) {
        this.mypara = m;
    }

    def GBdialog() {
        dialog = false
    }

    def GBdialog1() {
        dialog1 = false
    }

    def insert() {
        def conn = null
        SimpleDateFormat sdf_draft = new SimpleDateFormat("yyyy-MM-dd")
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1))
            conn.connection.autoCommit = false
            println "select zhangtid from YZ_DA_ZTcontrast where zhangtname='" + zhaochegs + "'"
            def pdgs = conn.firstRow("select zhangtid from YZ_DA_ZTcontrast where zhangtname='" + zhaochegs + "'")
            if (pdgs == null) {
                mypara.msg("所选公司不对")
                return
            }
//            if (zhaochefzr.toString().equals('') || zhaochefzr == null) {
//                mypara.msg("找车责任人为必填项")
//                return
//            }
            if (zhaochesfd.toString().equals('') || zhaochesfd == null) {
                mypara.msg("始发地为必填项")
                return
            }
            if (zhaochemdd.toString().equals('') || zhaochemdd == null) {
                mypara.msg("目的地为必填项")
                return
            }
            if (zhaochexxdz.toString().equals('') || zhaochexxdz == null) {
                mypara.msg("详细地址为必填项")
                return
            }
            if (zhaochesl.toString().equals('') || zhaochesl == null) {
                mypara.msg("车数量为必输项")
                return
            }
            if (zhaocheds.toString().equals('') || zhaocheds == null) {
                mypara.msg("吨数为必输项")
                return
            }
            def pjds = conn.firstRow("SELECT convert(decimal(23,2),CAST(" + zhaocheds + " AS DECIMAL(10, 2)) / CAST(" + zhaochesl + " AS DECIMAL(10, 2))) AS Result")
            if (pjds == null || pjds == 0) {
                mypara.msg("检查车辆或吨数数值")
                return
            }
            carlist=[]
            for (int i = 0; i < Integer.parseInt(zhaochesl); i++) {
                conn.execute "insert into db_purchaseCar(Date,Company,Typesof,Ogigin,Address,Destination," +
                        "Notes,Createname,Createdate,State,zhangtid,ds)values('" + createdate + "','" + zhaochegs + "','" + zhaochelx + "','" + zhaochesfd + "'," +
                        "'" + zhaochemdd + "','" + zhaochexxdz + "','" + zhaochebz + "','" + mypara.set.user.name + "',getDate(),'请确认','" + pdgs.zhangtid + "'," + pjds.Result + ")"
                def zcjh = conn.firstRow("SELECT SCOPE_IDENTITY() AS id");
                select1(conn, zcjh.id)
            }
            conn.commit()
            mypara.msg("保存成功")
            zckz = false //找车控制
            bckz = true //保存控制
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def zhaocar() {
        def conn = null
        SimpleDateFormat sdf_draft = new SimpleDateFormat("yyyy-MM-dd")
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1))
            conn.connection.autoCommit = false
            if (lbselectrow == null) {
                mypara.msg("请选择数据源")
                return
            }
            if (!lbselectrow.State.toString().equals("请确认")) {
                mypara.msg("不是请确认状态不能找车")
                return
            }
            conn.execute "update db_purchaseCar  set State='未找车' where id=" + lbselectrow.nid + ""
            conn.commit()
            mypara.msg("确认成功")
            lbselectrow.State = '未找车'
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def delete() {
        if (lbselectrow == null) {
            mypara.msg("请选择数据源")
            return
        }
        if (!lbselectrow.State.toString().equals("取消找车")&&!lbselectrow.State.toString().equals("请确认")) {
            mypara.msg("不是可删除状态")
            return
        }
        def conn = null
        SimpleDateFormat sdf_draft = new SimpleDateFormat("yyyy-MM-dd")
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1))
            conn.connection.autoCommit = false
            conn.execute"delete db_purchaseCar where id="+lbselectrow.nid+""
            conn.commit()
            mypara.msg("删除成功")
            carlist.remove(lbselectrow)
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def quxiaocar() {
        if (lbselectrow == null) {
            mypara.msg("请选择数据源")
            return
        }
        def conn = null
        SimpleDateFormat sdf_draft = new SimpleDateFormat("yyyy-MM-dd")
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1))
            conn.connection.autoCommit = false
            def xiaoxi
            conn.execute "update db_unapprovedSalesOrder set reviewStatus=2 where voucherCode='cgrk" + lbselectrow.nid + "' and reviewStatus=0"
            println "update db_unapprovedSalesOrder set reviewStatus=2 where voucherCode='cgrk" + lbselectrow.nid + "' and reviewStatus=0"
            def czid = conn.firstRow("select id from db_unapprovedSalesOrder where voucherCode='cgrk" + lbselectrow.nid + "' and reviewStatus=2")
            if (czid != null) {
                conn.execute "update db_CarSearchPlan set nStatus=6 where account =" + czid.id + ""
                def cxid = conn.firstRow("select id,xiaoxi,curator from db_CarSearchPlan where account =" + czid.id + "")
                if (cxid != null) {
                    def cxspr = "select spusercode from wsd_spjl where functioncode='db_CarSearchPlan' and gnnid='" + cxid.id + "'"
                    def cxsprpd = conn.rows("select spusercode from wsd_spjl where functioncode='db_CarSearchPlan' and gnnid='" + cxid.id + "' and spresult in(0,1)")
                    conn.eachRow(cxspr) {
                        def cxbz = conn.firstRow("select bz from wsd_user where code='" + it.spusercode + "'")
//                        def cxbz=conn.firstRow("select bz from wsd_user where code='104'")
                        //    enterpriseWechat(cxbz.bz.toString(), '''"title":"取消找车抄送消息","description":"<div class=\'gray\'>''' + currentTime + '''</div><div class=\'highlight\'>''' + cxid.xiaoxi + ''' ,已找车通知</div>","url":"http://c1.cnu.com.cn:8189/wsdsjmcloud-v12/resources/huoquid.jsp?type=6","btntxt":"详情"''')
                        enterpriseWechat(cxbz.bz.toString(), ''' "articles" : [{ "title" : "取消找车通知","description" : "''' + cxid.xiaoxi + ''' 请知晓。",}]''')
                    }
                    if (cxsprpd.size() == 0) {
                        def cxzcz = "select b.code,b.bz from wsd_usertogroup a left join wsd_user b on a.usercode=b.code where a.groupcode='c04'"
                        conn.eachRow(cxzcz) {
                            def cxbz = conn.firstRow("select bz from wsd_user where code='" + it.code + "'")
                            //    enterpriseWechat(cxbz.bz.toString(), '''"title":"取消找车抄送消息","description":"<div class=\'gray\'>''' + currentTime + '''</div><div class=\'highlight\'>''' + cxid.xiaoxi + ''' ,已找车通知</div>","url":"http://c1.cnu.com.cn:8189/wsdsjmcloud-v12/resources/huoquid.jsp?type=6","btntxt":"详情"''')
                            enterpriseWechat(cxbz.bz.toString(), ''' "articles" : [{ "title" : "取消找车通知","description" : "''' + cxid.xiaoxi + ''' 请知晓。",}]''')
                        }
                    }
                    conn.execute "update db_purchaseCar  set State='取消找车' where id=" + lbselectrow.nid + ""
                    conn.execute "delete db_CarSearchPlan where id='" + cxid.id + "'"
                    conn.execute "delete wsd_spjl  where functioncode='db_CarSearchPlan' and gnnid='" + cxid.id + "' "
                    conn.execute "delete wsd_spmsg  where functioncode='db_CarSearchPlan' and gnnid='" + cxid.id + "'"
                }
            }
            conn.commit()
            mypara.msg("取消成功")
            lbselectrow.State = '取消找车'
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def dialog1() {
        dialog1 = true
    }

    def select() {
        carlist = []
        def conn = null
        SimpleDateFormat sdf_draft = new SimpleDateFormat("yyyy-MM-dd")
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1))
            def chaxun = "select id, convert(varchar(23),Date,23) as Date,Company,Typesof,Head,Ogigin,Address,Destination,Notes,Createname,convert(varchar(23),Createdate,23) as Createdate,State,zhangtid,ds from db_purchaseCar where 1=1"
            if (cxzcksdate != null && cxzxjsdate != null) {
                chaxun = chaxun + " and convert(varchar(23),Date,23)>='" + cxzcksdate + "' and convert(varchar(23),Date,23)<='" + cxzxjsdate + "'"
            }
            if (cxzcksdate == null && cxzxjsdate != null) {
                chaxun = chaxun + " and convert(varchar(23),Date,23)<='" + cxzxjsdate + "'"
            }
            if (!cxzczdr.toString().equals('') && cxzczdr != null) {
                chaxun = chaxun + " and Createname='" + cxzczdr + "'"
            }
            if (!cxzcfzr.toString().equals('') && cxzcfzr != null) {
                chaxun = chaxun + " and Head='" + cxzcfzr + "'"
            }
            chaxun = chaxun + "  order by Date desc "
            conn.eachRow(chaxun) {
                def t = ["nid": it.id, "Date": it.Date, "Company": it.Company, "Typesof": it.Typesof, "Head": it.Head, "Ogigin": it.Ogigin, "Address": it.Address, "Destination": it.Destination, "Notes": it.Notes, "Createname": it.Createname, "Createdate": it.Createdate, "State": it.State, "zhangtid": it.zhangtid, "ds": it.ds]
                carlist.add(t)
            }
            dialog1 = false
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def select1(def conn, def id) {

        SimpleDateFormat sdf_draft = new SimpleDateFormat("yyyy-MM-dd")
        try {
            def chaxun = "select id, convert(varchar(23),Date,23) as Date,Company,Typesof,Head,Ogigin,Address,Destination,Notes,Createname,convert(varchar(23),Createdate,23) as Createdate,State,zhangtid,ds from db_purchaseCar where 1=1"
            chaxun = chaxun + " and id=" + id + " order by Date desc "
            conn.eachRow(chaxun) {
                def t = ["nid": it.id, "Date": it.Date, "Company": it.Company, "Typesof": it.Typesof, "Head": it.Head, "Ogigin": it.Ogigin, "Address": it.Address, "Destination": it.Destination, "Notes": it.Notes, "Createname": it.Createname, "Createdate": it.Createdate, "State": it.State, "zhangtid": it.zhangtid, "ds": it.ds]
                carlist.add(t)
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    def dialog() {
        dialog = true
        zhaochelx = '采购入库找车'
        createdate = currentTime
        zhaochegs = '' //找车公司
        zhaochefzr = '' //找车负责人
        zhaochesfd = '' //找车始发地
        zhaochemdd = '' //找车目的地
        zhaochebz = '' //找车备注
        zhaochexxdz = '' //找车始发地详细地址
    }

    def czwczcfzr(str) {
        def conn = null
        def arr = []
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1))
            def chaxun = "select b.name from wsd_usertogroup a left join wsd_user b on a.usercode=b.code where a.groupcode='c04' and b.name like '%" + str + "%' "
            conn.eachRow(chaxun) {
                arr = arr + it.name
            }
            return arr
        } catch (Exception e) {
            println(e.toString())
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def czwczth(str) {
        def conn = null
        def arr = []
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1))
            def chaxun = "select zhangtname from YZ_DA_ZTcontrast where  zhangtname like '%" + str + "%'"
            conn.eachRow(chaxun) {
                arr = arr + it.zhangtname
                zhaochegs = it.zhangtname
            }
            return arr
        } catch (Exception e) {
            println(e.toString())
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def enterpriseWechat(String code, String content) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        String responseContent = null;
        HttpGet hh = new HttpGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww1fcfe32b52380005&corpsecret=mks8JaMxS5htfd1iCRuKsBhEwmwWN0L_68urQ819-K0");
        try {
            //调用HttpClient对象的execute方法执行请求;
            httpResponse = httpClient.execute(hh);
            //获取请求响应对象和响应Entity;
            HttpEntity httpEntity = httpResponse.getEntity();
            //从响应对象中获取响应状态，从响应Entity中获取响应内容;
            if (httpEntity != null) {
                responseContent = EntityUtils.toString(httpEntity, "UTF-8");
            }
            def slurper = new JsonSlurper()
            def states = slurper.parseText(responseContent)
            def access_token = states['access_token']
            String json = '''{"touser" : "''' + code + '''","msgtype" : "news","agentid" : 1000003,"news" : {''' + content + '''},"enable_id_trans": 0,"enable_duplicate_check": 0}'''
            println json
            HttpPost ss = new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token + "")
            StringEntity se = new StringEntity(json, "UTF-8");
            ss.setEntity(se);
            ss.setHeader("Accept", "application/json");
            ss.setHeader("Content-Type", "application/json;charset=utf-8");
            httpResponse = httpClient.execute(ss);
            HttpEntity httpEntity1 = httpResponse.getEntity();
            //6、从响应对象中获取响应状态，从响应Entity中获取响应内容;
            if (httpEntity != null) {
                responseContent = EntityUtils.toString(httpEntity1, "UTF-8");
                println responseContent
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭响应对象;
                if (httpResponse != null) {
                    httpResponse.close();
                }
                //关闭HttpClient.
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


